package com.findviewbydream.evil.eda.Fragment.Menu;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.findviewbydream.evil.eda.Activity.AboutActivity;
import com.findviewbydream.evil.eda.Activity.FeedBackActivity;
import com.findviewbydream.evil.eda.Activity.FlowCallbackActivity;
import com.findviewbydream.evil.eda.Activity.OverAnswerActivity;
import com.findviewbydream.evil.eda.Activity.ShareActivity;
import com.findviewbydream.evil.eda.Activity.WebActivity;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.EventBus.CloseLeftEvent;
import com.findviewbydream.evil.eda.EventBus.UserInformationEvent;
import com.findviewbydream.evil.eda.R;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.yuyh.easyadapter.recyclerview.EasyRVAdapter;
import com.yuyh.easyadapter.recyclerview.EasyRVHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import cn.iwgang.familiarrecyclerview.FamiliarRecyclerView;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Fragment.Menu
 * 时间：16-7-11 下午7:53
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：主界面左侧菜单
 ********************************************/
public class LeftMenu extends Fragment
{
    private static final String[] items =
            {"已答列表", "用户分享"
                    , "流量兑换记录", "软件使用说明"
                    , "用户反馈", "关于软件"};

    private static final int[] imgs =
            {R.drawable.left_menu_over, R.drawable.left_menu_share
                    , R.drawable.left_menu_flowcallback, R.drawable.left_menu_instructions
                    , R.drawable.left_menu_feedback, R.drawable.left_menu_about};

    private View view;
    private CircleImageView userImg;
    private TextView userName;
    private TextView userPhoneNum;
    private RelativeLayout topLayout;
    private FrameLayout setIP;
    private TextView allFow;
    private TextView todayFow;
    private FamiliarRecyclerView recyclerView;

    private static LeftMenu leftMenu;

    private Adapter adapter;
    private ArrayList<ItemBean> list;

    /**
     * 入口函数
     *
     * @return
     */
    public static LeftMenu newInstance()
    {
        if (leftMenu == null)
            leftMenu = new LeftMenu();

        return leftMenu;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.leftmenu_fragment, container, false);
        initView(view);

        setTopLayout();/*设置顶部信息,每次开启都应刷新,在drawLayout里写刷新*/

        setRecyclerView();/*设置左侧菜单项目*/

        setSetIP();/*设置ip地址*/

        toNetWork();/*初始化连接*/

        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view)
    {
        userImg = (CircleImageView) view.findViewById(R.id.userImg);
        userName = (TextView) view.findViewById(R.id.userName);
        userPhoneNum = (TextView) view.findViewById(R.id.userPhoneNum);
        topLayout = (RelativeLayout) view.findViewById(R.id.topLayout);
        allFow = (TextView) view.findViewById(R.id.allFow);
        todayFow = (TextView) view.findViewById(R.id.todayFow);
        recyclerView = (FamiliarRecyclerView) view.findViewById(R.id.recyclerView);
        setIP = (FrameLayout) view.findViewById(R.id.setIP);
    }


    /*EventBus -> 注册*/
    @Override
    public void onStart()
    {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    /*EventBus -> 销毁*/
    @Override
    public void onStop()
    {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 设置顶部的文本信息
     * 用户头像
     * 用户名
     * 用户手机号
     * 本月总计获得流量
     * 今日总计获得流量
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UserInformationEvent event)
    {
        if (event.update)
        {
            toNetWork();
        }
    }

    /**
     * 更新用户信息网络链接
     */
    private void toNetWork()
    {
        OkHttpUtils.post().url(Data.IP + "IntegralServlet")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", UserData.getUserIMEI())
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        Utils.Toast("用户信息加载失败");
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        if (!response.equals("null"))
                        {
                            String[] ss = response.split(Data.BREAKSTRING);
                            UserData.setFlow(Integer.valueOf(ss[0]));
                            UserData.setTodayFlow(Integer.valueOf(ss[1]));
                        }
                        else
                        {
                            UserData.setFlow(0);
                            UserData.setTodayFlow(0);
                        }
                        setTopLayout();
                    }
                });
    }

    /**
     * 设置用户信息
     */
    @SuppressLint("SetTextI18n")
    private void setTopLayout()
    {
        if (UserData.getUserImg().isEmpty())
            Utils.Glide(R.drawable.eda, userImg);
        else
            Utils.Glide(UserData.getUserImg(), userImg);

        userName.setText("用户名:" + UserData.getUserName());
        userPhoneNum.setText("用户手机:" + UserData.getUserPhoneNum());
        allFow.setText("本月总计获取\n" + UserData.getFlow() + "M流量");
        todayFow.setText("今日总计获取\n" + UserData.getTodayFlow() + "M流量");
    }

    /**
     * 设置ip
     */
    private void setSetIP()
    {
        setIP.setOnClickListener(view1 -> {
            final View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.set_ip, null);
            new AlertDialog.Builder(getContext()).setTitle("设置ip地址").setView(dialogView)
                    .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                    .setPositiveButton("确认", (dialogInterface, i) -> {
                        EditText editText = (EditText) dialogView.findViewById(R.id.editText);
                        Data.IP = editText.getText().toString();
                    }).show();
        });
    }


    /**
     * 设置RecyclerView
     */
    private void setRecyclerView()
    {
        list = new ArrayList<>();
        for (String item : items)
            list.add(new ItemBean(item, ""));
        adapter = new Adapter(getActivity(), list, R.layout.leftmenu_item_1, R.layout.leftmenu_item_2);
        recyclerView.setAdapter(adapter);
        recyclerView.setOnItemClickListener((familiarRecyclerView, view1, position) -> {
            EventBus.getDefault().post(new CloseLeftEvent(true));
            switch (items[position])
            {
                /*case "首页":
                    startActivity(new Intent(getActivity(), ItemListActivity.class));
                    break;*/

                case "已答列表":
                    startActivity(new Intent(getActivity(), OverAnswerActivity.class));
                    break;

                case "用户分享":
                    startActivity(new Intent(getActivity(), ShareActivity.class));
                    break;

                case "流量兑换记录":
                    startActivity(new Intent(getActivity(), FlowCallbackActivity.class));
                    break;

                case "软件使用说明":
                    startActivity(new Intent(getActivity(), WebActivity.class)
                            .putExtra(WebActivity.URL, Data.IP + "app/instructions.html")
                            .putExtra(WebActivity.TITLE, "软件使用说明"));
                    break;

                case "用户反馈":
                    startActivity(new Intent(getActivity(), WebActivity.class)
                            .putExtra(WebActivity.URL, Data.IP + "app/feedback.html?phone=18832030507")
                            .putExtra(WebActivity.TITLE, "用户反馈"));
                    break;

                case "关于软件":
                    startActivity(new Intent(getActivity(), AboutActivity.class));
                    break;
            }
        });
    }

    private class Adapter extends EasyRVAdapter<ItemBean>
    {
        public Adapter(Context context, List<ItemBean> list, int... layoutIds)
        {
            super(context, list, layoutIds);
        }

        @Override
        public int getLayoutIndex(int position, ItemBean item)
        {
            return Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT_WATCH ? 1 : 0;
        }

        @Override
        protected void onBindData(EasyRVHolder viewHolder, int position, ItemBean item)
        {
            TextView textView = viewHolder.getView(R.id.leftmenu_item_textView);
            textView.setText(item.getTitle());
            ImageView imageView = viewHolder.getView(R.id.leftmenu_item_img);
            Utils.Glide(imgs[position], imageView);
        }
    }

    private class ItemBean
    {
        private String title;
        private String imgPath;

        public ItemBean(String title, String imgPath)
        {
            this.title = title;
            this.imgPath = imgPath;
        }

        public String getTitle()
        {
            return title;
        }

        public void setTitle(String title)
        {
            this.title = title;
        }

        public String getImgPath()
        {
            return imgPath;
        }

        public void setImgPath(String imgPath)
        {
            this.imgPath = imgPath;
        }
    }


/*
    private class Adapter extends RecyclerView.Adapter<ViewHolder>
    {
        @Override
        public int getItemViewType(int position)
        {
            if (items[position].isEmpty())
                return R.layout.leftmenu_item_2;
            else
                return R.layout.leftmenu_item_1;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View view = LayoutInflater.from(getActivity())
                    .inflate(viewType, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position)
        {
            if (!items[position].isEmpty())
                holder.tag.setText(items[position]);
        }

        @Override
        public int getItemCount()
        {
            return items.length;
        }
    }

    private class ViewHolder extends RecyclerView.ViewHolder
    {
        private ImageView img;
        private TextView tag;

        public ViewHolder(View itemView)
        {
            super(itemView);
            img = (ImageView) itemView.findViewById(R.id.leftmenu_item_img);
            tag = (TextView) itemView.findViewById(R.id.leftmenu_item_textView);
        }
    }
*/


}
